<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/4
 * Time: 16:24
 */

namespace app\api\controller;


use app\admin\model\live\LiveChannel;
use app\admin\model\SysAdmin;
use app\api\model\dynamic\DynamicM;
use app\api\model\DynamicFlow;
use app\common\controller\Base;
use app\common\controller\ClientAuth;
use app\common\model\ApiResponse;
use app\common\model\app\AppStartPage;
use app\common\model\app\AppVersion;
use app\common\model\app\Banner;
use app\common\model\teacher\Teacher;
use app\common\model\teacher\TeacherEssay;
use app\common\model\teacher\TeacherSpeaking;
use app\common\lib\wechat\WechatApi;
use Curl\Curl;
use think\Cache;
use think\Env;
use think\Validate;
use think\Request;


class App extends Base
{
    /**
     * Banner接口
     *
     * @return ApiResponse
     */
    public function banner() {
        $form = $this->getAndCheckForm([
            ['page_code', 'require|^\\d+$', '参数不能为空|参数类型不正确'],
        ]);

        $banners = Banner::apiList($form['page_code']);

        return ApiResponse::success($banners);
    }

    public function start_page() {
        $re = AppStartPage::getRand();
        return ApiResponse::success($re);
    }

    /**
     * getStockData
     * 从新浪获取股票数据
     *
     * @author zhengkai
     * @date 2017-08-23
     *
     * @todo v1.4.1废弃
     *
     * @param string $code 股票代码
     * @return array
     */
    private function getStockData($code)
    {
        $sinaApi = 'http://hq.sinajs.cn/';

        $curl = new Curl();
        $curl->get($sinaApi, ['list'=>$code]);
        $sourceData = $curl->response;

        if ($curl->error) {
            $result = ['code'=>400, 'data'=>'服务器请求出错'];
        } else {
            // 编码转换
            $data = iconv("gb2312","utf-8//IGNORE", $sourceData);

            // 提取数据
            preg_match('/="(.*?)"/', $data, $str);
            $result = ['code'=>200, 'data'=>explode(',', $str[1])];
        }

        return $result;
    }

    /**
     * stock_index
     * app首页股票指数数据接口
     * @api http://xxx/api/app/stock_index
     *
     * @author zhengkai
     * @date 2017-08-23
     *
     * @todo v1.4.1废弃
     *
     * @return \think\response\Json
     */
    public function stock_index()
    {
        // 上证指数
        $szzs = $this->getStockData('s_sh000001');
        if ($szzs['code']!=200) {
            $szzs_data = [];
        } else {
            $szzs_data = [
                'name' => $szzs['data'][0], // 指数名称
                'point' => sprintf("%.2f", $szzs['data'][1]), // 当前点数
                'price' => sprintf("%.2f", $szzs['data'][2]), // 当前价格
                'adr' => $szzs['data'][3].'%', // 涨跌率
            ];
        }


        // 深圳成指
        $szcz = $this->getStockData('s_sz399001');
        if ($szcz['code']!=200) {
            $szcz_data = [];
        } else {
            $szcz_data = [
                'name' => $szcz['data'][0], // 指数名称
                'point' => sprintf("%.2f", $szcz['data'][1]), // 当前点数
                'price' => sprintf("%.2f", $szcz['data'][2]), // 当前价格
                'adr' => $szcz['data'][3].'%', // 涨跌率
            ];
        }

        // 创业板指
        $cybz = $this->getStockData('s_sz399006');
        if ($cybz['code']!=200) {
            $cybz_data = [];
        } else {
            $cybz_data = [
                'name' => $cybz['data'][0], // 指数名称
                'point' => sprintf("%.2f", $cybz['data'][1]), // 当前点数
                'price' => sprintf("%.2f", $cybz['data'][2]), // 当前价格
                'adr' => $cybz['data'][3].'%', // 涨跌率
            ];
        }

        $result = [
            'szzs' => $szzs_data,
            'szcz' => $szcz_data,
            'cybz' => $cybz_data
        ];

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * 首页数据打包（微信版）
     *
     * @return ApiResponse
     */
    public function index_data_wechat() {

        $data = [];

        $curriculum = new \app\api\model\curriculum\Curriculum();
        $data['videos'] = $curriculum->get_recommend_video();

        $data['teachers'] = Teacher::rand(3);
        $data['speakings'] = TeacherSpeaking::apiList(3, 0);
        $data['banners'] = Banner::apiList(Banner::PAGE_MAIN);

        return ApiResponse::success($data);
    }

    /**
     * 首页数据打包（APP）
     * 微信端去除(banner/掌乾看盘/名师推荐/掌乾学堂) modify cc 2018-10-16
     * @return ApiResponse
     */
    public function index_data_app() {

        $uid = checkUserToken(false);

        $data = [];

        $curriculum = new \app\api\model\curriculum\Curriculum();
        $data['curriculum'] = $curriculum->queryRecommendCurriculum(3, $uid)->getData()['data'];

        // todo 废弃
        // $data['live'] = (new \app\api\model\live\Live())->get_live_list_index();

        //$data['teachers'] = Teacher::recommended(10, $uid); // 老师
        // $data['speakings'] = TeacherSpeaking::apiList(3, 0); // 专栏 todo 停用
        //$data['banners'] = Banner::apiList(Banner::PAGE_MAIN); // 轮播图
        $data['news'] = TeacherEssay::getTypeNewsList(config('news_col.news'), 3); // 资讯
        // $data['news'] = TeacherEssay::apiList(3,0,0,2, config('news_col.news'),false,false, $uid,0); // 资讯
        $lives_temp = LiveChannel::apiList(1,1,LiveChannel::STATUS_LIVE, $uid);
        $lives=$lives_temp['data'];
        $data['current_live'] = $lives[0] ?? (object)null; // 直播
        /*
        $data['dynamics'] = DynamicM::getLimitDynamic($uid, 1); // 看盘
        foreach ($data['dynamics'] as &$val) {
            $val['content'] = str_cut($val['content'], 240);
        }
        */

        $data['teacher_news'] = (new News())->point()->data['data']; // 观点
        //$data['school_col'] = News::getSubCatalog(config('news_col.school')); // 学堂栏目

        $data['ios_examining'] = Env::get('ios.examining', false);

        return ApiResponse::success($data);
    }

    /**
     * 首页数据打包（PC）
     *
     * @todo v1.4.1废弃
     *
     * @return ApiResponse
     */
    public function index_data_pc() {
        $data = [];

        $data['banners'] = Banner::apiList(Banner::PAGE_PC_MAIN);
        $data['essays'] = TeacherEssay::listTop(6);

        $curriculum = new \app\api\model\curriculum\Curriculum();
        $data['curriculum'] = $curriculum->queryRecommendCurriculum(8)->getData()['data'];
        $data['teachers'] = Teacher::recommended(4);

        return ApiResponse::success($data);
    }

    /**
     * 获取可用的客服
     *
     * @return ApiResponse
     */
    public function get_customer_service() {

        checkUserToken(true);

        $service = SysAdmin::getService();
        if ($service) return ApiResponse::success(['service' => $service]);
        else return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'当前没有客服在线');
    }

    /**
     * 获取app最新版本
     *
     * @return ApiResponse
     */
    public function latest_version() {

        $form = $this->getAndCheckForm([
            ['code', 'require|integer',],
            ['platform', '^[1-2]$', 'platform取值超范围'],
        ]);

        $re = AppVersion::latestVersion($form['code'], intval($form['platform']??AppVersion::PLATFORM_ANDROID));

        return ApiResponse::success($re);
    }

    /**
     * week_calendar
     * 周历数据接口
     * @api http://xxx/api/other/week_calendar
     *
     * @author zhengkai
     * @date 2017-10-26
     * @version v1.1
     *
     * @return \think\response\Json
     */
    public static function week_calendar()
    {
        $currDate = date('Y-m-d'); // 当前日期
        $startWeek = 1; // 一周开始时间
        $currWeek = date('w', strtotime($currDate)); // 获取当前周几
        //获取本周开始日期，如果0，则表示周日，减去 6 天
        $startDate = date('Y-m-d', strtotime($currDate.'-'.($currWeek?($currWeek-$startWeek):6).' days'));

        // 星期转换
        $weekArr = ['日', '一', '二', '三', '四', '五', '六'];
        $arr = [];
        for ($i=0; $i<=6; $i++) {
            $date = date('Y-m-d', strtotime("{$startDate} +{$i} days"));
            $week = $weekArr[date('w', strtotime($date))];

            $arr[] = [
                'date' => $date, // 日期
                'week' => '星期'.$week, // 星期
                'is_curr' => ($date===date('Y-m-d', time()))?1:0 // 是否为今天
            ];
        }

        $result = $arr;

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * web_index_live
     * pc端web版首页直播数据接口
     * @api http://xxx/api/web/index/live
     *      date 非必填 直播节目日期，格式：0000-00-00
     *
     * @author zhengkai
     * @date 2017-11-01
     * @version v1.1
     *
     * @todo v1.4.1废弃
     *
     * @return \think\response\Json
     */
    public function web_index_live()
    {
        $form = input('post.');
        if (array_key_exists('date', $form) || !empty($form['date'])) {
            $date = $form['date'];
        } else {
            $date = '';
        }

        // 周历
        $week_calendar = $this->week_calendar();
        $week_calendar = $week_calendar->getData();
        $week_calendar = $week_calendar['data'];

        // 直播节目
        $live = new \app\api\model\live\Live();
        $live = $live->query_live($date)->getData();
        $live = $live['data'];

        $result = [
            'week_calendar' => $week_calendar,
            'live' => $live,
        ];

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * web_index_news
     * pc端web版首页热门资讯、最新资讯数据接口
     * @api http://xxx/api/web/index/news
     *
     * @author zhengkai
     * @date 2017-11-02
     * @version v1.1
     *
     * @todo v1.4.1废弃
     *
     * @return \think\response\Json
     */
    public function web_index_news()
    {
        $news = new \app\api\model\News();

        return $news->get_news();
    }

    /**
     * dynamic
     * 名师动态数据接口
     * @api http://xxx/api/dynamic
     *      POST
     *          limit 选填 数据条数，默认10
     *
     * @author zhengkai
     * @date 2018-01-12
     * @version v1.3
     *
     * @return \think\response\Json
     */
    public function dynamic()
    {
        $uid = checkUserToken(false);

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['page', '^\\d+$', 'page参数类型不正确'],
            ['limit', '^\\d+$', 'limit参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));
        if (!isset($form['page'])) $form['page']=1;
        if (!isset($form['limit'])) $form['limit']=10;

        $data = new DynamicFlow();
        $result = $data->getDynamic($uid, $form['page'], $form['limit']);

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * 获取微信jssdk所需授权签名
     *
     * @return ApiResponse
     */
    public function wechat_jsapi_sign() {
        $form = $this->getAndCheckForm([
            ['url', 'require|url',],
        ]);
        $url = explode('#', $form['url'])[0];

        $data = WechatApi::makeSignature(['url' => $url]);
        return ApiResponse::success($data);
    }

    /**
     * dynamics
     * 掌乾动态(看盘)
     * @api http://xxx/api/app/dynamics
     *
     * @author zhengkai
     * @date 2018-05-10
     * @version 1.5
     *
     * @return ApiResponse
     */
    public function dynamics()
    {
        $uid = checkUserToken(false);

        $form = $this->getAndCheckForm([
            ['limit', 'integer', '参数类型不正确'],
        ]);

        if (!isset($form['limit'])) $form['limit'] = 3;

        $result = DynamicM::getLimitDynamic($uid, intval($form['limit']));

        return ApiResponse::success($result);
    }
}
